<template>
  <div class="app-container">
    <div class="form-container">
          <el-form ref="searchForm" :model="searchForm" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="4" :offset="2">
                    <el-form-item label="名称" prop="username">
                        <el-input v-model="searchForm.username" placeholder="请输入姓名"/>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="角色" prop="roleId">
                        <el-select clearable v-model="searchForm.roleId" placeholder="请选择类型">
                            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="仓库" prop="storeId">
                        <el-select clearable v-model="searchForm.storeId" placeholder="请选择仓库">
                            <el-option v-for="item in stores" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态" prop="status">
                        <el-select clearable v-model="searchForm.status" placeholder="请选择状态">
                            <el-option label="正常" value="1"></el-option>
                            <el-option label="禁用" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button icon="el-icon-search" type="primary" circle @click="getData" />
                  <el-button icon="el-icon-refresh-right" type="warning" size="medium" round @click="resetForm('searchForm')">
                      重置
                    </el-button>
              </el-col>
            </el-row>
        </el-form>
    </div>

    <div class="action">
      <el-button icon="el-icon-plus" type="primary" size="small" round @click="handleAdd">
        新建
        </el-button>
    </div>

    <el-table stripe border fit highlight-current-row
      :header-cell-style="{textAlign: 'center'}"
      :cell-style="{ textAlign: 'center' }"
      :data="users.slice((page - 1) * limit, page * limit)"
      :default-sort="{ prop: 'date', order: 'ascending' }">

      <el-table-column prop="id" label="ID" width="40" />
      <!-- <el-table-column prop="avatar" label="头像" width="70">
        <template slot-scope="scope">
           <el-avatar :src= "scope.row.avatar" />
      </template>
      </el-table-column> -->
     
      <el-table-column prop="username" label="姓名" width="80" />
      <el-table-column prop="sex" label="性别" width="50">
        <template slot-scope="scope">
        <span>{{ scope.row.sex == 0 ? '男':'女' }}</span>
      </template>
      </el-table-column>

      <el-table-column  prop="phoneNum" label="电话号码" min-width="90"/>
      <!-- <el-table-column prop="email" label="邮箱" min-width="100"/> -->
      <el-table-column prop="role.name" label="角色" />
      <el-table-column prop="store.name" label="管理仓库" />
      <el-table-column  prop="isEnable"  label="状态" width="60">
          <template slot-scope="{row}">
            <el-tag :type="row.isEnable | statusFilter">
              {{ row.isEnable == 1 ? '正常' : '禁用'}}
            </el-tag>
          </template>
        </el-table-column>

<!-- 
      <el-table-column label="创建时间"  prop="createTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ $dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="修改时间"  prop="updateTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ $dayjs(scope.row.updateTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column> -->
    
      <el-table-column label="操作"  min-width="120px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="small" circle @click="handleEdit(scope.row.id)"/>
          <!-- <template v-if="scope.row.role.id != 1"> -->
          
          <el-button v-if="scope.row.isEnable == 0"  type="success" icon="el-icon-check" size="small" circle @click="handleStatus(scope.row)"/>
          <el-button v-else type="warning"  icon="el-icon-minus" size="small" circle @click="handleStatus(scope.row)"/>
         
          <!-- </template> -->

          <el-button type="danger" icon="el-icon-delete" size="small" circle @click="handleDelete(scope.row,scope.$index + 1)"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getData"/>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {  0: 'danger', 1: 'success'}
      return statusMap[status]
    }
  },
  data() {
    return {
      users: [],
      total: 0,
      listLoading: true,
      page: 1,
      limit: 5,

      roles:[],
      stores:[],
      searchForm: {
        username: "",
        roleId:"",
        storeId:"",
        status:'',
      }
    };
  },
  methods: {
    async getData() {  
      // 获取用户列表
      let res = await this.$store.dispatch('user/getList',this.searchForm) 
      if(res.code == 1) {
          this.users = res.data 
          this.total = this.users.length 
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
      // 获取角色列表
      res = await this.$store.dispatch('role/getList') 
      if(res.code == 1) {
          this.roles = res.data
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
      // 获取仓库列表
      res = await this.$store.dispatch('myStore/getList',{name:'',address:''}) 
      if(res.code == 1) {
          this.stores = res.data
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
    },
    handleEdit(id) {
      this.$router.push({path:"/edit/user/edit",query: {id}},)
    },
    handleDelete({id,username}) {
      this.$confirm("此操作将永久删除用户 "+username+" 信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(async () => {
          const res = await this.$store.dispatch('user/deleteUser',id) 
          if(res.code == 1) {
            // 根据 id 寻找数据在 数组中的 下标
            const index = this.users.map(item => item.id).indexOf(id)
            // 删除这一行
            this.users.splice(index,1)
            // 数组长度减 1 动态绑定到分页器
            this.total--;
            this.$message({ type: "success",  message: res.msg, duration: 1000});
          }else{
            this.$message({ type: "error",  message: res.msg, duration: 1000});
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除"});
        });
    },
    handleAdd() {
      this.$router.push({path:"/add/user/add"})
    },
    handleStatus({id,username,isEnable}){
      let msg = isEnable == 1 ? '禁用':'激活'
      this.$confirm("此操作将 "+msg+" 用户: "+username+" 状态信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(async () => {
          const res = await this.$store.dispatch('user/isEnableUser',{id,isEnable}) 
          let msg = isEnable == 1 ? '禁用':'激活'
          if(res.code == 1) {
              // 根据 id 寻找数据在 数组中的 下标
              const index = this.users.map(item => item.id).indexOf(id)
              // 修改这一行状态
              this.users[index].isEnable =  isEnable == 1 ? 0 : 1
            
              this.$message({ type: "success",  message: msg + res.msg, duration: 1000})
          }else{
            this.$message({ type: "error", message: msg + res.msg});
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消"+msg});
        });
    },
    resetForm(searchForm) {
      this.$refs[searchForm].resetFields()
      this.$message({  message: '清空成功', type: 'success'})
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style lang="scss" scoped>
  .form-container {
    display: flex;
    width: 100%;
    align-items:center;
    justify-content:center;
  }
  .search {
    width: 100%;
    text-align: center;
    padding-left: 20px;
  }
  .search-more {
    width: 100%;
  }
  .action {
    width: 100%;
    padding-bottom: 10px;
    text-align: left;
  }
</style>
